import request from "@/utils/request";
import { useUserStore } from "@/stores/user";
import md5 from "md5";
import sha1 from "crypto-js/sha1";

// 签名生成工具函数
function generateSignParams(config) {
  // 这里的 APP_ID 与 APP_SECRET 请替换为真实值
  const APP_ID = "azRnLvxl";
  const APP_SECRET = "76d9baa27803da36d07ec4972fd041b32fcec40d"; // 来自后端配置

  const timestamp = Date.now().toString();
  const nonce =
    Math.random().toString(36).substring(2, 15) +
    Math.random().toString(36).substring(2, 15);

  const params = JSON.parse(JSON.stringify(config?.params || {}));
  const query = Object.keys(params)
    .map((key) => `${key}=${params[key]}`)
    .join("&");

  const data =
    !config?.data || config?.data instanceof FormData
      ? ""
      : JSON.stringify(config.data || "");

  // const queryError = /error/.test(window.location.href)
  //   ? `&error=${Date.now()}`
  //   : "";
  const queryError = "";

  const signature = `${query}${queryError}${data}appId=${APP_ID}&nonce=${nonce}&timestamp=${timestamp}${APP_SECRET}`;
  const signatureMd5 = md5(sha1(signature).toString()).toString();
  const signatureParam = `appId=${APP_ID}&nonce=${nonce}&timestamp=${timestamp}`;

  return {
    timestamp,
    nonce,
    sign: signatureMd5,
    appParam: signatureParam,
    appId: APP_ID,
  };
}

// 添加通用请求头
export function addCommonHeaders(
  config,
  isLogin = false,
  isDetailedBattery = false
) {
  const { sign, appParam, appId } = generateSignParams(config);
  const userStore = useUserStore();

  // 通用头部
  config.headers = {
    ...(config.headers || {}),
    "Accept-Language": "zh-CN",
    // 按对方约定的大小写
    "Cfmoto-X-Sign": sign,
    "Cfmoto-X-Param": appParam,
    "Cfmoto-X-Sign-Type": "0",
    appid: appId,
    "x-app-info":
      "MOBILE|Android|9|KLICEN_APP|2.2.5|Dalvik/2.1.0 (Linux; U; Android 9; V2199GA Build/PQ3A.190705.09121602)|720*1280|1|100|wifi|vivo",
  };

  // 登录时使用Basic认证
  if (isLogin) {
    config.headers.Authorization = "Basic bWNrOjEyMzQ1Ng==";
    config.headers["Content-Type"] = "application/json";
  } else {
    // 其他API调用使用token
    config.headers.Authorization = `bearer ${userStore.userInfo?.token || ""}`;
  }

  return config;
}

/**
 * 随机生成一个中国境内的城市坐标
 * 支持每次生成不同城市和位置
 */

function generateRandomChinaGeo() {
  const CITIES = [
    { city: "110000", name: "北京市", lat: 39.9042, lng: 116.4074 },
    { city: "310000", name: "上海市", lat: 31.2304, lng: 121.4737 },
    { city: "440100", name: "广州市", lat: 23.1291, lng: 113.2644 },
    { city: "510100", name: "成都市", lat: 30.5786, lng: 104.0648 },
    { city: "420100", name: "武汉市", lat: 30.5928, lng: 114.3055 },
    { city: "220100", name: "长春市", lat: 43.8361, lng: 125.3245 },
    { city: "650100", name: "乌鲁木齐市", lat: 43.8256, lng: 87.6168 },
    { city: "540100", name: "拉萨市", lat: 29.6602, lng: 91.1321 },
    { city: "230100", name: "哈尔滨市", lat: 45.8038, lng: 126.5348 },
    { city: "330100", name: "杭州市", lat: 30.2741, lng: 120.1551 },
    { city: "440300", name: "深圳市", lat: 22.5431, lng: 114.0579 },
    { city: "320100", name: "南京市", lat: 32.0603, lng: 118.7969 },
    { city: "370100", name: "济南市", lat: 36.6519, lng: 117.1220 },
    { city: "130100", name: "石家庄市", lat: 38.0428, lng: 114.5149 },
    { city: "640100", name: "银川市", lat: 38.4865, lng: 106.2280 },
    { city: "630100", name: "西宁市", lat: 36.6211, lng: 101.7808 },
    { city: "450100", name: "南宁市", lat: 22.8170, lng: 108.3665 },
    { city: "520100", name: "贵阳市", lat: 26.5986, lng: 106.6301 },
    { city: "210100", name: "沈阳市", lat: 41.7969, lng: 123.4086 },
    { city: "610100", name: "西安市", lat: 34.3416, lng: 108.9402 }
  ];

  const randomCity = CITIES[Math.floor(Math.random() * CITIES.length)];

  const EARTH_RADIUS = 6371000; // 米
  const radius = 1000; 
  const angle = Math.random() * 2 * Math.PI;
  const distance = Math.sqrt(Math.random()) * radius;

  const deltaLat = distance * Math.cos(angle) / EARTH_RADIUS;
  const deltaLng = distance * Math.sin(angle) / (EARTH_RADIUS * Math.cos(randomCity.lat * Math.PI / 180));

  const newLat = randomCity.lat + (deltaLat * 180 / Math.PI);
  const newLng = randomCity.lng + (deltaLng * 180 / Math.PI);

  return {
    city: randomCity.city,
    latitude: newLat.toFixed(6),
    longitude: newLng.toFixed(6)
  };
}


// 获取验证码
export function getVerifyCode(phone) {
  const config = {
    url: `/v1.0/mine/cfmotoservermine/authCode/${phone}`,
    method: "get",
  };

  return request(config);
}

// 登录
export function login(data) {
  const loginData = {
    authCode: data.code,
    phone: data.phone,
    ...generateRandomChinaGeo(),
    province: "",
    referralCode: "",
  };

  const config = {
    url: "/v1.0/mine/cfmotoservermine/user/loginByPhone",
    method: "post",
    data: loginData,
  };

  return request(config);
}
